
import React, {useRef,useState,useEffect,useCallback }  from 'react';

import {useNavigate } from "react-router-dom";


import style from './style/COCdetails.module.scss'
import CardBox from '../CardBox';
import COCchangeTag from './COCchangeTag';


import {useSelector,useDispatch } from 'react-redux'
import type { StoreState, StoreDispatch } from '../../store'
// 异步任务
import { getalluser,getDoctor,getprogettos,addorder } from '../../store/modules/cost/costuser'
// 同步任务
import { changetoadd } from '../../store/modules/cost/costuser'


import { Select, Table, Button,Space,message,Input } from 'antd';
import type { ColumnsType } from 'antd/es/table';





// // 表格数据类型
interface DataType {

    key: React.Key;
    _id?:any
    username: string;
    avatar: string;
    IDcardtype: string,
    IDcartnumber: string,
    about: string,
    address: string
    tel: number,
    visitID: number,
    wxname: string,
}



function COCadd() {


    // 派发任务
    const dispatch: StoreDispatch = useDispatch();

    // 仓库状态
    const {costuser:{userlist,Doctorlist,progettos,isadd,isaddstr,toadd}} = useSelector((state: StoreState)=>state)
    
    // 路由切换
    const navigate = useNavigate();


    
    // 存储选中key值（一个数组）
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    
    // 医生
    const [selectedDoctorc, setSelectedDoctorc] = useState<React.Key[]>([]);

    // 就诊项目
    const [selectedProgetto, setSelectedProgetto] = useState<React.Key[]>([])
    

    // 存储最终需要添加的内容
    let addObj = useRef<any>()


    const [messageApi, contextHolder] = message.useMessage();



    useEffect(() => {
        if (toadd && isadd) {
            messageApi.open({
                type: 'success',
                content: isaddstr,
            })
            setTimeout(() => {
                navigate({ pathname: `/Costmsg/CostOutConsume` })
                dispatch(changetoadd())
            },2000)
        }
        if (toadd && !isadd) {
            messageApi.open({
                type: 'error',
                content: isaddstr,
            })
            return
        }
    },[toadd,isadd])


    // 选中事件就诊人
    const onChange = (newSelectedRowKeys: React.Key[]) => {
        addObj.current = {
            ...addObj.current,
            userid:newSelectedRowKeys[0]
        }
        setSelectedRowKeys(newSelectedRowKeys);
    };


    // 选中医生
    const changeDoctorc = (newSelectedRowKeys: React.Key[]) => {
        console.log('选中医生', newSelectedRowKeys[0]);
        addObj.current = {
            ...addObj.current,
            Doctorcid:newSelectedRowKeys[0]
        }
        setSelectedDoctorc(newSelectedRowKeys);

    };
    
    // 选中项目
    const changeProgetto = (newSelectedRowKeys: React.Key[],itemdata:any) => {
        console.log('选中项目: ', newSelectedRowKeys,itemdata);

        addObj.current = {
            ...addObj.current,
            Progetto: itemdata.map((item:any) => {
                return {
                        entryname: item.entryname,
                        price: item.price,
                        quantity: 1,
                        total:item.price
                    }
            })
        }
        setSelectedProgetto(newSelectedRowKeys)
    }

    // 选中就诊医院
    const changeHospital = useCallback((Hospital: string) => {
        console.log('选中就诊医院: ', Hospital);
        console.log('选中就诊医院: ', addObj);
        addObj.current = {
            ...addObj.current,
            Hospital
        }
    }, [])
    
    // 选中医院地址
    const changeHospitaladdress = useCallback((Hospitaladdress:string) => {
        console.log('选中医院地址: ', Hospitaladdress);
        console.log('选中医院地址: ', addObj);

        addObj.current = {
            ...addObj.current,
            Hospitaladdress
        }
    }, [])
    
    // 费用类型
    const changeCosttype = useCallback((Costtype:string) => {
        console.log('选中费用类型: ', Costtype);
        console.log('费用类型: ', addObj);

       addObj.current = {
            ...addObj.current,
            Costtype
        }
    }, [])

    // 选中业务类型
    const changeBusiness = useCallback((Business:string) => {
        console.log('选中业务类型: ', Business);
        console.log('选中业务类型: ', addObj);

        addObj.current = {
            ...addObj.current,
            Business
        }
    }, [])
    
    // 选中支付方式
    const changePayment = (newSelectedRowKeys:string) => {
        console.log('选中支付方式', newSelectedRowKeys);
        console.log('选中支付方式: ', addObj);

        addObj.current = {
            ...addObj.current,
            uocost:newSelectedRowKeys
        }
    }




    
    useEffect(() => {
        dispatch(getprogettos())
        dispatch(getDoctor({Department:'内科-肾内科'}))

    },[])

    // 输入框搜索事件
    let ref = useRef<any>(null)
    const getInputValue = () => {
        let value
        if (ref) {
            value = ref.current!.input.value
        }
        // 派发任务前先清除先前可能已经选择的用户信息
        if (value != '') {
            addObj.current = {
            ...addObj.current,
                userid:undefined
            }
            dispatch(getalluser({inptext:value}))
        }
        console.log(value);
        
    }
    
    // 确认添加
    const save = () => {
        addObj.current = {
            Hospital: "北京市第一人民医院/东院",
            Hospitaladdress: "北京市大兴区**路990号",
            Costtype:"西药费",
            Business:"门诊缴费",
            Department: "内科-肾内科",
            uocost: "余额",
            ...addObj.current,

        }
        if (!addObj.current.Doctorcid) {
            messageApi.open({
                type: 'error',
                content: '医生信息未选择',
            })
            return
        } else if (!addObj.current.userid) {
            messageApi.open({
                type: 'error',
                content: '就诊人未选择',
            })
            return
        } else if (addObj.current.Progetto?.length ==0 || (!addObj.current.Progetto)) {
            messageApi.open({
                type: 'error',
                content: '就诊项目未选择',
            })
            return
        }

        console.log("添加",addObj);
        dispatch(addorder(addObj))
        dispatch(changetoadd())

    }

    // 取消添加(退出)
    const out = () => {
        addObj.current = {}
        navigate({ pathname: `/Costmsg/CostOutConsume` })
    }

    // 根据科室获取医生信息，
    const getDepartment = (Department: string) => {
        // 切换科室医生并且存储当前科室信息，并且清除先前选择的医生信息
        addObj.current = {
            ...addObj.current,
            Department,
            Doctorcid:undefined
        }
        console.log(Department);
        dispatch(getDoctor({Department}))
    }


    // 就诊人表格
    const columns: ColumnsType<DataType> = [
        {
            title: '患者姓名',
            dataIndex: 'username',
        },
        {
            title: '患者头像',
            dataIndex: 'avatar',
            render: (data,item,index) => {
            // console.log('data',data,item,index);
            return (
                <img style={{width:36,height:36,borderRadius:16}} src={ item.avatar }></img>
            )
        }
        },
        {
            title: '微信昵称',
            dataIndex: 'wxname',
        },
        {
            title: '电话号码',
            dataIndex: 'tel',
        },
        {
            title: '证件类型',
            dataIndex: 'IDcardtype',
        },
        {
            title: '证件号码',
            dataIndex: 'IDcartnumber',
        },
        {
            title: '就诊号码',
            dataIndex: 'visitID',
        },
        {
            title: '居住地址',
            dataIndex: 'address',
        },
        {
            title: '关系',
            dataIndex: 'about',
        },
    ];
    // 选择医生表格
    const DoctorcColumns: ColumnsType<DataType> = [
        {
            title: '医生姓名',
            dataIndex: 'Doctorname',
        },
        {
            title: '医生头像',
            dataIndex: 'avatar',
            render: (data,item,index) => {
            // console.log('data',data,item,index);
            return (
                <img style={{width:36,height:36,borderRadius:16}} src={ item.avatar }></img>
            )
        }
        },
        {
            title: '院区',
            dataIndex: 'Courtyardarea',
        },
        {
            title: '职称',
            dataIndex: 'Doctorjob',
        },
        {
            title: '科室',
            dataIndex: 'Department',
        },
    ];

    // 就诊项目表格
    const ProgettoColumns: ColumnsType<DataType> = [
        {
            title: '项目名称',
            dataIndex: 'entryname',
        },
        {
            title: '单价',
            dataIndex: 'price',
        },
    ];

    return (
        <div>
            {contextHolder}

            <div className={ style.top}>
                <div className={ style.blueBox}></div>
                <span>订单添加</span>
            </div>  
            <CardBox title='添加就诊人'>
                <div>
                    <Space direction="vertical" size={12} style={{ marginBottom:"24px" }}>
                        {/* 搜索 */}
                        <div className='inp-box'>
                                <Input
                                placeholder="请输入病人姓名/就诊卡号"
                                style={{ width: "200px" }}
                                ref={ref}
                            />
                            <Button onClick={getInputValue} type="primary" style={{ marginLeft: "10px" }}>
                                搜索
                            </Button>
                        </div>
                    </Space>

                    <Table
                        // 就诊人表格配置项
                        columns={columns}
                        // 表格数据
                        dataSource={userlist}
                        // 分页器能实现的事件
                        pagination={false}
                        rowSelection={{
                            // 选中事件
                            onChange,
                            // 选中的key值数组
                            selectedRowKeys
                        }}
                    />
                </div>
                
            </CardBox>
            {/* 添加就诊信息 */}
            <CardBox title='就诊信息'>
                <div>
                    <div className={ style.BigBox }>
                    <div className={style.ChangeDivBox}>
                        <COCchangeTag title='就诊医院'>
                            <Select
                                defaultValue={ "北京市第一人民医院/东院"}
                                style={{ width: 120 }}
                                onChange={changeHospital}
                                options={[
                                    { value: '北京市第一人民医院/东院', label: '北京市第一人民医院/东院' },
                                    { value: '广州市第一人民医院/东院', label: '广州市第一人民医院/东院' },
                                    { value: '广州市第二人民医院/西院', label: '广州市第二人民医院/西院' },
                                ]}
                            /> 
                        </COCchangeTag>
                        <COCchangeTag title='费用类型'>
                            <Select
                                defaultValue={ "西药费" }
                                style={{ width: 120 }}
                                onChange={changeCosttype}
                                options={[
                                    { value: '西药费', label: '西药费' },
                                    { value: '中药费', label: '中药费' },
                                    { value: '住院费', label: '住院费' },
                                ]}
                            /> 
                        </COCchangeTag>
                    </div>
                    <div className={style.ChangeDivBox}>
                        <COCchangeTag title='医院地址'>
                            <Select
                                defaultValue={ "北京市大兴区**路990号"}
                                style={{ width: 120 }}
                                onChange={changeHospitaladdress}
                                options={[
                                    { value: '北京市大兴区**路990号', label: '北京市大兴区**路990号' },
                                    { value: '广州市天河区**路100号', label: '广州市天河区**路100号' },
                                    { value: '广州市黄埔区**路200号', label: '广州市黄埔区**路200号' },
                                ]}
                            /> 
                        </COCchangeTag>
                        <COCchangeTag title='业务类型'>
                            <Select
                                defaultValue={ "门诊缴费"}
                                style={{ width: 120 }}
                                onChange={changeBusiness}
                                options={[
                                    { value: '门诊缴费', label: '门诊缴费' },
                                    { value: '购药缴费', label: '购药缴费' },
                                    { value: '住院缴费', label: '住院缴费' },
                                ]}
                            /> 
                        </COCchangeTag>

                    </div>
                    
                </div>
                <div className={style.ChangeDivBox}>
                        <COCchangeTag title='就诊科室'>
                            <Select
                                defaultValue={ "内科-肾内科"}
                                style={{ width: 120 }}
                                onChange={getDepartment}
                                options={[
                                    { value: '内科-肾内科', label: '内科-肾内科' },
                                    { value: '外科-牙科', label: '外科-牙科' },
                                    { value: '内科-神经科', label: '内科-神经科' },
                                    { value: '外科-皮肤科', label: '外科-皮肤科' },
                                ]}
                            /> 
                        </COCchangeTag>
                        <div className={ style.custom } style={{marginBottom:40}}>
                            {/* 医生表格 */}
                            <Table
                                columns={DoctorcColumns}
                                dataSource={Doctorlist}
                                pagination={false}
                                style={{ width: '80%' }}
                                scroll={{ y: 400 }}
                                rowSelection={{
                                    onChange:changeDoctorc,
                                    selectedRowKeys:selectedDoctorc
                                }}
                            />
                        </div>
                        <COCchangeTag title='就诊项目'></COCchangeTag>
                        <div className={ style.custom }>
                            {/* 表格 */}
                            <Table
                                columns={ProgettoColumns}
                                dataSource={progettos}
                                pagination={false}
                                style={{ width: 500 }}
                                scroll={{ y: 400 }}
                                rowSelection={{
                                    selectedRowKeys: selectedProgetto,
                                    onChange:changeProgetto
                                }}
                            />
                        </div>

                </div>
                </div>
            </CardBox>
            <CardBox title='订单信息'>
                <div>
                    <COCchangeTag title='支付方式'>
                        <Select
                            defaultValue={ "余额"}
                            style={{ width: 120 }}
                            onChange={changePayment}
                            options={[
                                { value: '余额', label: '余额' },
                                { value: '微信支付', label: '微信支付' },
                                { value: '支付宝', label: '支付宝' },
                                { value: '现金', label: '现金' },
                            ]}
                        /> 
                    </COCchangeTag>
                </div>
            </CardBox>
            <Space size={18}>
                <Button type="primary" onClick={save}>保存</Button>
                <Button onClick={out}>取消</Button>
            </Space>
        </div>
    )
}

export default COCadd;